import {designComponent, onMounted, reactive} from "@peryl/react-compose";
import {MicroList} from "../components/MicroList";
import {microApp} from "../microApp";
import {pathJoin} from "@peryl/utils/pathJoin";
import {iMicroTokenInfo} from "@peryl/micro-web";
import {i18n} from "plain-design";
import {RouterPrivateLocale} from "./RouterPrivate.locale";

i18n.setLangs(RouterPrivateLocale);

/*
定义路由：
microApp.route.definePageRoute({ route: '/public/order/:publicCode', path: 'react-base/demo/demo-public-layout-page', });
访问路由：
http://localhost:4001/micro-web-react-base/public/order/123
*/
/**
 * Private路由渲染
 * @author  韦胜健
 * @date    2024/5/9 12:16
 */
export const RouterPublic = designComponent({
  setup() {

    const state = reactive({ tokenInfo: null as null | iMicroTokenInfo });

    onMounted(async () => {

      /*一般情况下不会没有路由信息，这里做类型保护处理*/
      if (!microApp.route.state.route) {return;}

      /*页面路径*/
      let path = pathJoin('/' + microApp.route.state.route.path + '/');
      /*页面查询参数*/
      const query = microApp.route.state.route.query;

      /*检查是否有匹配的预定义路由*/
      console.log('public path -->> ', { path });
      const pageRouteConfigMatch = microApp.route.matchPageRoute(path);
      if (!pageRouteConfigMatch) {
        microApp.openTab({ path: 'react-base/core/404-page', label: '', data: { closable: false, path, query } });
        state.tokenInfo = {} as any;
        return;
      }
      /*合并预定义参数、地址查询参数以及动态路由参数*/
      const pageParams = { ...pageRouteConfigMatch.params, ...query, ...pageRouteConfigMatch.routeParams, path };
      state.tokenInfo = {} as any;
      microApp.openTab({ path: pageRouteConfigMatch.path, label: pageRouteConfigMatch.title || '', data: pageParams });
    });

    return () => (
      !!state.tokenInfo && <div className="app-private">
        <div className="app-content">
          <div className="app-content-inner">
            <MicroList tokenInfo={state.tokenInfo}/>
          </div>
        </div>
      </div>
    );
  },
});
